<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<style type="text/css">
			*{margin:0;padding:0;}
			canvas{background:#f0f0f0}
		</style>
	</head>
	<body>
		<canvas id="canvas" width='800' height='400'></canvas>
	</body>
</html>
<script type="text/javascript">
	var Game = function(){
		this.canvas = document.getElementById("canvas"),
		this.context = this.canvas.getContext("2d"),
		
		this.fps = 60,
		this.lastFrameTime = 0,
		
		/*用于背景图片加载*/
		this.background = new Image(),
		/*用于暂停开始*/
		this.paused = false,
		this.PAUSED_TIME = 200,
		
		/*用于背景移动*/
		this.STARTING_BACKGROUND_OFFSET = 2,
		this.backgroundOffset = this.STARTING_BACKGROUND_OFFSET,
		this.bgVelocity = 0;
	}
Game.prototype = {
	draw : function(now){
		this.drawBackground();
		this.backgroundoff();
	},
	drawBackground : function(){
		this.context.translate(-this.backgroundOffset,0);
		this.context.drawImage(this.background,0,0);
		this.context.drawImage(this.background,this.background.width,0);
		this.context.translate(this.backgroundOffset,0);
	},
	backgroundoff : function(now){
		this.backgroundOffset += this.STARTING_BACKGROUND_OFFSET;
      if (this.backgroundOffset < 0 || 
          this.backgroundOffset > this.background.width) {
         this.backgroundOffset = 0;
      }
	},
	getFps : function(now){
		var fps = 1 / (now-this.lastFrameTime) * 1000;
//		console.log(fps);
		return fps;
	},
	gamepaused : function(){
		this.paused = !this.paused;
	},
	animate : function(now){
		if(suchen.paused){
			setTimeout(function(){
				requestAnimationFrame(suchen.animate);
			},suchen.PAUSED_TIME);
		}else{
			suchen.getFps(now);
			suchen.lastFrameTime = now;
			suchen.draw(now);
			requestAnimationFrame(suchen.animate);
		}
	},
	init : function(){
      this.background.src = 'img/background.png';
      this.background.onload = function (e) {
         suchen.startGame();
      };
	},
	startGame : function(){
		this.drawBackground();
		requestAnimationFrame(this.animate);
	}
}

	
	var suchen = new Game();
	suchen.init();
	
	window.addEventListener("keydown",function(e){
		var key = e.keyCode;
		if(key===27){
			suchen.gamepaused();
		}
	})
</script>